<template>
	<view class="page__content">
		<web-view ref="webviewRef" v-if="pageConfig.show" class="webview-container" fullscreen="false"
			@message="handleWebviewMessage" :src="pageConfig.path">
		</web-view>
	</view>
</template>

<script setup lang="ts">
	import { reactive, computed, onMounted, ref, nextTick, getCurrentInstance } from 'vue'
	import { onLoad, onShow, onHide, onBackPress, onUnload } from '@dcloudio/uni-app'
	import { useMainStore, useQmsStore, usePermissionStore, useUserStore } from '@/store';
	const qmsStore = useQmsStore();
	const mainStore = useMainStore();
	const permissionStore = usePermissionStore();
	const userStore = useUserStore();
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, onAllComplete, onError } = useRequestQueue();


	let pageConfig = reactive({
		show: true, //  控制是否展示 webview
		path: null, // webview 展示地址
		isInCurrentPage: true, // 判断是否处在当前页
	});

	const webviewRef = ref<any>(null)

	let currentWebview = ref<any>(null)

	console.log(qmsStore.orderConfig.order_info);
	const orderInfo = uni.$utils.deepClone(qmsStore.orderConfig.order_info);
	// 获取相关的信息
	let findData = permissionStore.moduleInfoAll[0]["Node"].find(item => item.APPFunID == orderInfo.APPFunID);
	// 获取展示连接
	pageConfig.path = findData.AP_Link;

	const UserInfo = computed(() => {
		return userStore.UserInfo
	})

	// 初始化基础配置项
	const initConfig = () => {

		let sendConfig = {
			GetDocumentInfo: null,
			GetUserInfo: null,
			SetServiceIP: null,
			GetBtnPermission: null,
			// GetDeviceName: null
		} as any;

		// 打开的单据, 首页直接点击单据，快捷进入
		if (uni.getStorageSync('GetDocumentInfo')) {
			// 疑惑点：拿到的时字符串格式，传入之后，可以直接 点出来；关键是转对象 会报错 Uncaught SyntaxError: Unexpected identifier
			let GetDocumentInfo = uni.getStorageSync('GetDocumentInfo');

			sendConfig['GetDocumentInfo'] = GetDocumentInfo;
		};

		// 获取用户信息
		sendConfig['GetUserInfo'] = UserInfo.value;
		// 设置 IP 信息
		sendConfig['SetServiceIP'] = {
			serverIP: mainStore.appConfigInfo.serverIP,
			IPAgreement: mainStore.appConfigInfo.IPAgreement
		};

		// 处理按钮权限数据
		// 如果有按钮权限
		if (findData['IconApprove'].length) {
			sendConfig['GetBtnPermission'] = findData['IconApprove'];
		};

		sendDataToHtml('vm.page_initConfig', JSON.stringify(sendConfig));



	}

	let routes = getCurrentPages(); //当前页面栈

	const baseScreenListenName = computed(() => {
		return 'order_choice_' + routes.length
	});


	const processImageUrl = (url) => { // 处理图片链接地址
		if (uni.$utils.isEmpty(url)) '';
		url = url.trim();

		function urlRegular(value) {
			return /^((https|http|ftp|rtsp|mms):\/\/)/
				.test(value)
		}

		let isHttp = urlRegular(url);
		if (isHttp) {
			return url;
		} else {
			return mainStore.appConfigInfo.IPAgreement + mainStore.appConfigInfo.serverIP + url;
		}

	}

	// ✅ 接收 HTML 发来的消息
	const handleWebviewMessage = (event : any) => {
		try {
			const data = event.detail?.data?.[0] || {}
			console.log('收到 HTML 消息:', data)

			switch (data.action) {
				case "baseScreen":

					mainStore.openBaseScreen({
						...data.param,
						listeningName: baseScreenListenName.value
					});
					break;

				case "ToScan":
					uni.$utils.$scanPopup.openScan({
						onlyFromCamera: false,
						scanType: ["qrCode", "barCode"],
						success: (res) => {

							sendDataToHtml('vm.GetToScanInfo', JSON.stringify(res));
						}
					});
					break;
				// 如果是打开作业指导书
				case "showPopup":
					uni.$utils.showLoading("开始加载文件...");
					// 预览文件
					uni.downloadFile({
						url: processImageUrl(data.path),
						success: function (res) {

							uni.$utils.showLoading("准备打开文件...");
							// 仅在 App 端使用 plus API
							var filePath = plus.io.convertLocalFileSystemURL(res.tempFilePath);


							console.log(JSON.stringify(filePath))
							uni.openDocument({
								filePath: filePath,
								showMenu: true,
								success: function (res) {
									uni.$utils.hideLoading();
								}
							});
						}
					})
					break;
				case "GoBack":
					pageConfig.show = false;
					uni.navigateTo({
						url: '/commonPage/Tool/TransitBackPage'
					});
					break;
				// 打开
				case "openDeviceControl":
					uni.navigateTo({
						url: '/st_qms/page_device/page_control'
					});
					break;
				default:
					break;
			}
		} catch (e) {
			console.error('消息解析错误:', e)
		}
	}
	// 获取当前页面的 webview 实例
	const pages = getCurrentPages()
	const page = pages[pages.length - 1]

	// ✅ 向 HTML 页面发送数据
	const sendDataToHtml = (methodName : string, params ?: any) => {
		try {

			setTimeout(function () {
				console.log(page.$getAppWebview().children());
				const targetWebview = page.$getAppWebview().children()[0]

				if (!targetWebview) {
					console.warn('未找到 WebView 实例')
					return
				}

				// 序列化参数为字符串
				const paramStr = params ? JSON.stringify(params) : ''

				// 拼接 evalJS 调用字符串
				// 注意：HTML 端方法名 + 参数必须是合法 JS 表达式
				const jsCode = params
					? `${methodName}(${paramStr})`
					: `${methodName}()`

				console.log('执行 HTML 函数:', jsCode)
				targetWebview.evalJS(jsCode)
			}, 1000);
		} catch (err) {
			console.error('调用 WebView 方法失败:', err)
		}
	};


	onShow(() => {
		// 强制
		plus.screen.lockOrientation('landscape-primary');
		pageConfig.isInCurrentPage = true;
	});

	onHide(() => {
		pageConfig.isInCurrentPage = false;
	})

	onLoad(() => {

		initConfig();


		// 监听已连接设备的数据
		uni.$on("send:bluetooth-data", (ret) => {
			// 要求只有当前页为最顶层才能操作
			if (pageConfig.isInCurrentPage) {
				console.log('收到蓝牙数据，发送给 HTML：', ret)
				sendDataToHtml('vm.setRange', JSON.stringify(ret.num));

			}
		})

		uni.$on(baseScreenListenName.value, (ret : any) => {
			console.log(ret);



			sendDataToHtml('vm.GetBaseCreenBack', JSON.stringify(ret));

		})


	})
	onMounted(() => {
		// const pages = getCurrentPages()
		// const page = pages[pages.length - 1]
		// currentWebview.value = page.$getAppWebview()
		// console.log('当前 webview id:', currentWebview.value.id)


		// console.log(currentWebview.value.children());
		// pageConfig.show = true;
	})

	// 监听页面返回
	onBackPress((options : any) => {
		console.log(options);
		if (options.from == 'backbutton') {
			return true;
		} else {
			return false;
		}
	});

	onUnload(() => {
		// 当页面显示的时候，如果缓存中有下载文件的地址，则删掉该文件
		if (uni.getStorageSync('NeedRemove')) {
			uni.removeSavedFile({
				filePath: uni.getStorageSync('NeedRemove'),
				complete: function (res) {
					uni.removeStorageSync('NeedRemove')
				}
			});
		}

		uni.$off(baseScreenListenName.value)

	})
</script>

<style lang="scss">
	.page__content {
		height: 100vh;
		background-color: #f9f9f9;
	}
</style>